package com.roamer.audition.server.repository.base;

import com.roamer.audition.server.entity.base.LogicDeleteBaseEntity;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 通用CRUD实现类
 *
 * @author roamer
 * @version V1.0
 * @date 2019-08-21 01:01
 */
public class LogicDeleteRepositoryImpl<T extends LogicDeleteBaseEntity, ID extends Serializable>
        extends SimpleJpaRepository<T, ID> implements LogicDeleteRepository<T, ID> {

    public LogicDeleteRepositoryImpl(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
    }

    @Transactional
    @Override
    public void logicDelete(T entity) {
        Assert.notNull(entity, "Entity must not be null!");
        entity.setDeleted(true);
        // flush后处于游离态
        super.saveAndFlush(entity);
    }

    @Transactional
    @Override
    public void logicDeleteAll(Iterable<? extends T> entities) {
        Assert.notNull(entities, "Entities must not be null!");

        for (T entity : entities) {
            logicDelete(entity);
        }
    }
}

